package commit

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"practice/config"
	"practice/internal/model/dao"
)

type Commit struct {
	UserId     int    `form:"userId" json:"userId" xml:"userId"  binding:"required"`
	TravelId   int    `form:"travelId" json:"travelId" xml:"travelId" binding:"required"`
	Intro      string `form:"intro" json:"intro" xml:"intro" binding:"required"`
	CommitTime string `form:"commitTime" json:"commitTime" xml:"commitTime" binding:"required"`
}

func CommitAdd(c *gin.Context) {
	var json Commit
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	userId, _ := c.Get("userId")
	a := userId.(uint)
	travelId := json.TravelId
	intro := json.Intro
	commitTime := json.CommitTime
	var user dao.User
	config.DB.Where("id=?", a).First(user)
	if user.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该用户不存在"})
		return
	}
	var travel dao.Travel
	config.DB.Where("id=?", travelId).First(travel)
	if travel.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该攻略不存在"})
		return
	}
	commit := dao.UserCommit{
		UserId:     int(a),
		TravelId:   travelId,
		CommitTime: commitTime,
		Intro:      intro,
	}
	config.DB.Create(&commit)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "评论成功",
		"data": commit.ID,
	})
}
